package cn.com.infohold.smartcity.activity.Warrant;

import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.reflect.TypeToken;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import cn.com.infohold.smartcity.R;
import cn.com.infohold.smartcity.adapter.WarrantAdd_AppendAdapter;
import cn.com.infohold.smartcity.api.HttpEvent;
import cn.com.infohold.smartcity.api.SDK;
import cn.com.infohold.smartcity.api.bean.AppendageBean;
import cn.com.infohold.smartcity.api.bean.ChengBaoFangBean;
import cn.com.infohold.smartcity.api.bean.FaBaoFangBean;
import cn.com.infohold.smartcity.api.bean.LandInfoBean;
import cn.com.infohold.smartcity.api.bean.LandResult;
import cn.com.infohold.smartcity.api.bean.ListResult;
import cn.com.infohold.smartcity.api.bean.WarrantBean;
import cn.com.infohold.smartcity.data.XmlData;
import cn.com.infohold.smartcity.parent.ParentActivity;
import cn.com.infohold.smartcity.utils.DialogUtils;
import cn.com.infohold.smartcity.utils.GsonUtil;
import cn.com.infohold.smartcity.utils.RecyclerViewDivider;
import cn.com.infohold.smartcity.utils.RequestCode;
import cn.com.infohold.smartcity.view.WheelView;
import common.annotation.ViewInject;
import library.utils.DisplayUtil;

/**
 * Created by Monsoon on 2017/11/8.
 */
public class WarrantAdd_Activity extends ParentActivity{

    @ViewInject(R.id.ib_back)
    ImageButton ib_back;
    @ViewInject(R.id.et_docnumber)
    EditText et_docnumber;
    @ViewInject(R.id.et_contractnumber)
    EditText et_contractnumber;
    @ViewInject(R.id.tv_contractfullname)
    TextView tv_contractfullname;
    @ViewInject(R.id.tv_contractname)
    TextView tv_contractname;
    @ViewInject(R.id.tv_contractcode)
    TextView tv_contractcode;

    @ViewInject(R.id.tv_contractorname)
    TextView tv_contractorname;
    @ViewInject(R.id.tv_contractorcode)
    TextView tv_contractorcode;
    @ViewInject(R.id.tv_contractorcardid)
    TextView tv_contractorcardid;
    @ViewInject(R.id.tv_contractortel)
    TextView tv_contractortel;
    @ViewInject(R.id.tv_contractoraddress)
    TextView tv_contractoraddress;

    @ViewInject(R.id.tv_contracttype)
    TextView tv_contracttype;
    @ViewInject(R.id.et_landquantity)
    EditText et_landquantity;
    @ViewInject(R.id.et_area)
    EditText et_area;
    @ViewInject(R.id.et_startdate)
    EditText et_startdate;
    @ViewInject(R.id.et_enddate)
    EditText et_enddate;
    @ViewInject(R.id.et_certificatecode)
    EditText et_certificatecode;
    @ViewInject(R.id.et_certificatedate)
    EditText et_certificatedate;
    @ViewInject(R.id.et_certificateoffice)
    EditText et_certificateoffice;
    @ViewInject(R.id.rv_list)
    RecyclerView rv_list;
    @ViewInject(R.id.rv_appendlist)
    RecyclerView rv_appendlist;

    @ViewInject(R.id.btn_commit)
    Button btn_commit;

    private WarrantBean warrantBean;
    private List<FaBaoFangBean> fbList = new ArrayList<>();
    private List<ChengBaoFangBean> cbList = new ArrayList<>();
    private List<LandInfoBean> landList = new ArrayList<>();
    private List<AppendageBean> appendList = new ArrayList<>();

    String[] wayStr = new String[]{"转包","转让","入股","合作","租赁","互换"};
    private WarrantAdd_LandAdapter mAdapter;
    private WarrantAdd_AppendAdapter apAdapter;

    @Override
    protected Object inflateView() {
        return R.layout.activity_add_warrant;
    }

    @Override
    protected void initView(View anchor) {

        warrantBean = new WarrantBean();

        ib_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
                overridePendingTransitionFade();
            }
        });

        List<String> wayList = new ArrayList<>();
        Collections.addAll(wayList,wayStr);

        tv_contracttype.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DialogUtils.createNewSelectedDialog(WarrantAdd_Activity.this, "承包方式选择", new WheelView.OnWheelViewOkClickListener() {
                    @Override
                    public void onClick(View var1, int selectedIndex, String selectValue, List<Integer> selectIndexs, List<String> selectValues) {
                        if (tv_contracttype.getText().toString().equals(wayList.get(selectedIndex).toString())){
                            return;
                        }
                        tv_contracttype.setText(wayList.get(selectedIndex));

                    }
                },wayList,tv_contracttype.getText().toString(),false,false,true);
            }
        });

        btn_commit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                warrantBean.setDocnumber(et_docnumber.getText().toString());
                warrantBean.setContractnumber(et_contractnumber.getText().toString());
                warrantBean.setContracttype(tv_contracttype.getText().toString());
                warrantBean.setStartdate(et_startdate.getText().toString());
                warrantBean.setEnddate(et_enddate.getText().toString());
                warrantBean.setArea(Double.valueOf(et_area.getText().toString()));
                warrantBean.setCertificatecode(et_certificatecode.getText().toString());
                warrantBean.setCertificatedate(et_certificatedate.getText().toString());
                warrantBean.setCertificateoffice(et_certificateoffice.getText().toString());
                switch (XmlData.getInstance().getUserInfo().getRoles()){
                    case "4":
                        warrantBean.setStatus(2);
                        break;
                    case "3":
                        warrantBean.setStatus(5);
                        break;
                    case "2":
                        warrantBean.setStatus(8);
                        break;
                    default:
                        break;
                }
                warrantBean.setLandquantity(Integer.valueOf(et_landquantity.getText().toString()).intValue());
                warrantBean.setUserid(XmlData.getInstance().getUserInfo().getId());

                initData();

            }
        });

        getFabaoData();
        getChengbaoData();
        initLandRV();
        initAppendRV();
    }

    private void initLandRV(){
        int dividerHeight = DisplayUtil.dp2px(0);
        rv_list.setLayoutManager(new LinearLayoutManager(this));
        rv_list.addItemDecoration(new RecyclerViewDivider(dividerHeight));
        mAdapter = new WarrantAdd_LandAdapter(landList);
        rv_list.setAdapter(mAdapter);
    }

    private void initAppendRV(){
        int dividerHeight = DisplayUtil.dp2px(0);
        rv_appendlist.setLayoutManager(new LinearLayoutManager(this));
        rv_appendlist.addItemDecoration(new RecyclerViewDivider(dividerHeight));
        apAdapter = new WarrantAdd_AppendAdapter(appendList);
        rv_appendlist.setAdapter(apAdapter);
    }

    class WarrantAdd_LandAdapter extends RecyclerView.Adapter<WarrantAdd_LandAdapter.mViewHolder>{

        private List<LandInfoBean> mList;
        private boolean flag = true;

        public WarrantAdd_LandAdapter(List<LandInfoBean> mList) {
            this.mList = mList;
        }

        @Override
        public mViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            mViewHolder viewHolder = new mViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_warrantadd_land, parent, false));
            return viewHolder;
        }

        @Override
        public void onBindViewHolder(mViewHolder holder, int position) {

            LandInfoBean bean = mList.get(position);
            holder.tv_code.setText(bean.getCode());
            holder.tv_bgcode.setText(bean.getBgcode());
            holder.ll_item.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (flag == false){
                        holder.checkbox.setChecked(true);
                        flag = true;
                        warrantBean.setLandid(bean.getId());
                        appendList.clear();
                        appendList.addAll(bean.getAppendageBeanList());
                        initAppendRV();
                    }else {
                        holder.checkbox.setChecked(false);
                        flag = false;
                        warrantBean.setLandid("");
                    }
                }
            });
        }

        @Override
        public int getItemCount() {
            return mList.size();
        }

        class mViewHolder extends RecyclerView.ViewHolder{

            LinearLayout ll_item;
            CheckBox checkbox;
            TextView tv_code;
            TextView tv_bgcode;

            public mViewHolder(View itemView) {
                super(itemView);
                ll_item = (LinearLayout) itemView.findViewById(R.id.ll_item);
                checkbox = (CheckBox) itemView.findViewById(R.id.checkbox);
                tv_code = (TextView) itemView.findViewById(R.id.tv_code);
                tv_bgcode = (TextView) itemView.findViewById(R.id.tv_bgcode);
            }
        }
    }

    private void getFabaoData(){
        SDK.api().getFBList(1,15,"","","").postEvent(RequestCode.REQUEST_CODE_GET_FB_LIST);
    }

    private void getChengbaoData(){
        SDK.api().getCBList(15,1,"","","","").postEvent(RequestCode.REQUEST_CODE_GET_CB_LIST);
    }

    private void getLandDataById(String userid){
        SDK.api().getLandById(userid).postEvent(RequestCode.REQUEST_CODE_GET_LANDSBYID);
    }

    private void initData(){
        SDK.api().addWarrant(warrantBean).postEvent(RequestCode.REQUEST_CODE_ADD_WARRANT);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getData(HttpEvent<String> httpEvent){

        int requestCode = httpEvent.getRequestCode();
        if (requestCode != RequestCode.REQUEST_CODE_GET_FB_LIST
                && requestCode != RequestCode.REQUEST_CODE_GET_CB_LIST
                && requestCode != RequestCode.REQUEST_CODE_GET_LANDSBYID
                && requestCode != RequestCode.REQUEST_CODE_ADD_WARRANT) {
            return;
        }

        if (httpEvent.getState() != HttpEvent.STATE_SUCCESS) {
            return;
        } else {
            switch (requestCode){
                case RequestCode.REQUEST_CODE_GET_FB_LIST:
                    Type fbType = new TypeToken<LandResult<ListResult<FaBaoFangBean>>>(){}.getType();
                    LandResult<ListResult<FaBaoFangBean>> fbResult = GsonUtil.fromJson(httpEvent.getData(),fbType);
                    if (fbResult.getStatus().equals("1")){
                        List<FaBaoFangBean> list = fbResult.getResult().getList();
                        fbList.clear();
                        fbList.addAll(list);
                        List<String> fList = new ArrayList<>();
                        for (FaBaoFangBean bean : fbList){
                            fList.add(bean.getFullname());
                        }

                        tv_contractfullname.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                DialogUtils.createNewSelectedDialog(WarrantAdd_Activity.this, "发包方选择", new WheelView.OnWheelViewOkClickListener() {
                                    @Override
                                    public void onClick(View var1, int selectedIndex, String selectValue, List<Integer> selectIndexs, List<String> selectValues) {
                                        if (tv_contractfullname.getText().toString().equals(fList.get(selectedIndex).toString())){
                                            return;
                                        }

                                        FaBaoFangBean faBaoFangBean = fbList.get(selectedIndex);
                                        String contractName = fList.get(selectedIndex).toString();
                                        tv_contractfullname.setText(contractName);
                                        tv_contractname.setText(faBaoFangBean.getName());
                                        tv_contractcode.setText(faBaoFangBean.getCode());

                                        warrantBean.setContractingpartyid(faBaoFangBean.getId());

                                    }
                                },fList,tv_contractfullname.getText().toString(),false,false,true);
                            }
                        });
                    }

                    break;
                case RequestCode.REQUEST_CODE_GET_CB_LIST:
                    Type cbType = new TypeToken<LandResult<ListResult<ChengBaoFangBean>>>(){}.getType();
                    LandResult<ListResult<ChengBaoFangBean>> cbResult = GsonUtil.fromJson(httpEvent.getData(),cbType);
                    if (cbResult.getStatus().equals("1")){
                        List<ChengBaoFangBean> list = cbResult.getResult().getList();
                        cbList.clear();
                        cbList.addAll(list);
                        List<String> cList = new ArrayList<>();
                        for (ChengBaoFangBean bean : cbList){
                            cList.add(bean.getName());
                        }

                        tv_contractorname.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                DialogUtils.createNewSelectedDialog(WarrantAdd_Activity.this, "承包方代表", new WheelView.OnWheelViewOkClickListener() {
                                    @Override
                                    public void onClick(View var1, int selectedIndex, String selectValue, List<Integer> selectIndexs, List<String> selectValues) {
                                        if (tv_contractorname.getText().toString().equals(cList.get(selectedIndex).toString())){
                                            return;
                                        }

                                        ChengBaoFangBean chengBaoFangBean = cbList.get(selectedIndex);
                                        String contractName = cList.get(selectedIndex).toString();
                                        tv_contractorname.setText(contractName);
                                        tv_contractorcode.setText(chengBaoFangBean.getCode());
                                        tv_contractorcardid.setText(chengBaoFangBean.getCardid());
                                        tv_contractortel.setText(chengBaoFangBean.getTel());
                                        tv_contractoraddress.setText(chengBaoFangBean.getAddress());

                                        warrantBean.setContractorid(chengBaoFangBean.getId());

                                        getLandDataById(chengBaoFangBean.getId());

                                    }
                                },cList,tv_contractorname.getText().toString(),false,false,true);
                            }
                        });
                    }
                    break;
                case RequestCode.REQUEST_CODE_GET_LANDSBYID:
                    Type landType = new TypeToken<LandResult<List<LandInfoBean>>>(){}.getType();
                    LandResult<List<LandInfoBean>> landResult = GsonUtil.fromJson(httpEvent.getData(),landType);
                    if (landResult.getStatus().equals("1")){
                        List<LandInfoBean> result = landResult.getResult();
                        landList.clear();
                        landList.addAll(result);
                        initLandRV();
                    }

                    break;
                case RequestCode.REQUEST_CODE_ADD_WARRANT:
                    Type type = new TypeToken<LandResult<Map<String,String>>>(){}.getType();
                    LandResult<Map<String,String>> result = GsonUtil.fromJson(httpEvent.getData(),type);
                    Toast.makeText(this, result.getMessage(), Toast.LENGTH_SHORT).show();
                    if (result.getStatus().equals("1")){
                        finish();
                        overridePendingTransitionFade();
                    }
                    break;

                default:
                    break;
            }
        }
    }

}
